<script src="../../utils/config.js"></script>
<template>
  <div id="app">
    <div class="chat-app-main-container" v-if=" list.list&&list.list.length > 0">
      <div class="app-head">
        <p class="app-head-title">未读消息</p>
      </div>
      <ul class="app-body">
        <li>
          <div class="content">
            <p class="text text-line-2">
              <i class="el-icon-chat-dot-round icon-s"></i>
              {{ list.list[0].msg}}
            </p>
            <p class="time">
              {{ list.list[0].time | dateFormat}}
            </p>
          </div>
        </li>
        <li v-if="list.list&&list.list.length > 1">
          <div class="content">
            <p class="text text-line-2">
              <i class="el-icon-chat-dot-round icon-s"></i>
              {{ list.list[1].msg}}
            </p>
            <p class="time">
              {{ list.list[1].time | dateFormat}}
            </p>
          </div>
        </li>
        <li v-if="list.list&&list.list.length > 2">
          <div class="content">
            <p class="text text-line-2">
              <i class="el-icon-chat-dot-round icon-s"></i>
              {{ list.list[2].msg}}
            </p>
            <p class="time">
              {{ list.list[2].time | dateFormat}}
            </p>
          </div>
        </li>
      </ul>
      <div class="app-foot">
        <el-button type="text" @click="onClick">查看更多>>></el-button>
      </div>

    </div>
    <div v-else class="chat-app-main-pice">
      <blank picWidth="150px" title="暂无消息"></blank>
    </div>
  </div>
</template>

<script>
  import {getToken} from "@/utils/auth";
  import blank from "../../components/blank.vue";

  export default {
    name: "index",
    components: {
      blank
    },

    data() {
      return {
        userId: 0,
        booleM: false,
        key: '',
        token: '',
        websock: null, //建立的连接
        lockReconnect: false, //是否真正建立连接
        timeout: 200 * 1000, //200秒一次心跳
        timeoutObj: null, //心跳心跳倒计时
        serverTimeoutObj: null, //心跳倒计时
        timeoutnum: null,//断开 重连倒计时
        list: {}
      }
    },
    watch: {
      list: {
        handler() {
          this.list = this.$store.getters.messageList
        },
        deep: true
      }
    },
    mounted() {
      this.userId = this.$store.getters.userInfo.hospital_id
      this.key = this.$store.getters.userInfo.tenant_key
      this.token = getToken()
      this.init()
      this.list = this.$store.getters.messageList
      console.log(this.$store.getters.isNewOutpatien, "----------")
    },
    methods: {
      // //显示消息
      onClick() {
        this.$emit('message');
      }
      ,
      //建立连接
      init() {
        //初始化weosocket
        let Authorization = this.token
        let TID = this.userId
        let TenantKey = this.key
        //const wsuri = `ws://api.tianyizhushou.com/admin/message/connect`;
        const config = require('../../utils/config')
        const wsuri = config[process.env.NODE_ENV].wsUrl
        //建立连接
        this.websock = new (wsuri, [Authorization, TenantKey, TID]);
        //连接成功
        this.websock.onopen = this.onopen;
        //连接错误
        this.websock.onerror = this.onerror;
        //接收信息
        this.websock.onmessage = this.onmessage;
        //连接关闭
        this.websock.onclose = this.close;
      }
      ,
      //重新连接
      reconnect() {
        var that = this;
        if (that.lockReconnect) {
          return;
        }
        that.lockReconnect = true;
        //没连接上会一直重连，设置延迟避免请求过多
        that.timeoutnum && clearTimeout(that.timeoutnum);
        that.timeoutnum = setTimeout(function () {
          //新连接
          that.init();
          that.lockReconnect = false;
        }, 5000);
      }
      ,
      //重置心跳
      reset() {
        var that = this;
        //清除时间
        clearTimeout(that.timeoutObj);
        clearTimeout(that.serverTimeoutObj);
        //重启心跳
        that.start();
      }
      ,
      //开启心跳
      start() {
        var self = this;
        self.timeoutObj && clearTimeout(self.timeoutObj);
        self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
        self.timeoutObj = setTimeout(function () {
          //这里发送一个心跳，后端收到后，返回一个心跳消息
          self.websock.send("ping");
          self.serverTimeoutObj = setTimeout(function () {
            //超时关闭
            self.websock.close();
          }, self.timeout);
        }, self.timeout);
      }
      ,
      //连接成功事件
      onopen() {
        // this.send('发送数据');
        //提示成功
        console.log("连接成功11", 1);
        //开启心跳
        this.start();
      }
      ,
      //连接失败事件
      onerror(e) {
        console.log("连接发生错误44",);
        //重连
        this.reconnect();
      }
      ,
      //连接关闭事件
      close(e) {
        console.log("连接已关闭33",);
        //重连
        this.reconnect();
      }
      ,
      //接收服务器推送的信息
      onmessage(event) {
        console.log("收到服务器信息22", event.data,);
        console.log(typeof (event.data))
        //收到服务器信息，心跳重置
        var data, a, time, msg;
        if (event.data && event.data.length > 0 && event.data !== 'pong') {
          //data = typeof (event.data) === 'string' ? JSON.parse(event.data) : event.data
          data = JSON.parse(event.data)
          switch (data.type) {
            case 0:
              a = '系统消息'
              time = data.time
              msg = data.msg
              this.unshiftM(msg, time)
              this.list = this.$store.getters.messageList
              break
            case 1:
              a = '挂号'
              this.$store.dispatch("message/setIsNewOutpatienting", true)
              console.log(this.$store.getters.isNewOutpatien, "-=-=挂号-=-=-=-")
              break
            case 2:
              a = '收费'
              this.$store.dispatch("message/setIsNewPayting", true)
              console.log(this.$store.getters.isNewPay, "--------收费(药房)----------")
              break
            case 3:
              a = '发药'
              this.$store.dispatch("message/setIsNewDrugting", true)
              console.log(this.$store.getters.isNewDrug, "--------发药----------")
              break
            case 4:
              a = '收费'
              this.$store.dispatch("user/getInfo").then(()=>{
                this.$router.go(0)
              })
              console.log(this.$store.getters.isCharge, "--------收费(系统)----------")
              break
          }
        }

        this.reset();
      }
      ,
      unshiftM(msg, time) {
        let data = this.$store.getters.messageList;
        if (data.list) data.list.unshift(
          {
            msg: msg,
            time: time
          }
        );
        this.$store.dispatch("message/setMessageSetting", data)
      }
      ,
      unshiftIs(id) {
        let that = this
        let data = this.$store.getters.isNewOutpatien;
        console.log(this.$store.getters.isNewOutpatien, "----897979------")
        data.boole = true
        data.list.unshift(id);
        this.$store.dispatch("message/setIsNewOutpatienting", data)
        setTimeout(function () {
          console.log(that.$store.getters.isNewOutpatien, "-----*-**--**------")
        }, 1000)

      }
      ,
      //向服务器发送信息
      send(msg) {
        this.websock.send(msg);
      }
    }

  }
</script>

<style scoped lang="scss">
  @import "@/assets/scss/message/index.scss";
</style>
